<script setup>
  import { computed, onBeforeMount, ref, watch } from 'vue'
  import './style/base.css'
  import './style/index.css'
  import TodoHeader from './components/TodoList/TodoHeader.vue'
  import TodoMain from './components/TodoList/TodoMain.vue'
  import TodoFooter from './components/TodoList/TodoFooter.vue'

  // 提供数据
  const list = ref(JSON.parse(localStorage.getItem('todoList')) || [])
  const active = ref('All')

  // 新增
  const addTodo = (name)=> {
    list.value.unshift({
      id : list.value.length + 1,
      name,
      done: false
    })
  }

  // 编辑
  const changeDone = (id) =>{
    const todo = list.value.find((item)=> item.id === id)
    if(todo) {
      todo.done = !todo.done
    }
  }

  // 删除
  const delTodo = (id) =>{
    list.value = list.value.filter((item) => item.id !== id)
  }

  // 全选
  const checkAll = (value) => {
    list.value.forEach((item) => item.done = value)
  }

  // 筛选
  const changeActive = (val) => {
    active.value = val;
  }
  const select = computed(() => {
    if(active.value === 'Active') {
      return list.value.filter((item) => !item.done)
    } else if(active.value === 'Completed') {
      return  list.value.filter((item) => item.done)
    } else {
      return list.value
    }
  })
  // 清空已完成
  const clearCompleted = () => {
    list.value = list.value.filter((item) => !item.done)
  }

  // 本地存储
  watch(list, (value)=> {
    localStorage.setItem('todoList', JSON.stringify(value))
  },{deep: true})
</script>

<template>
  <div>
    <TodoHeader @addTodo="addTodo"></TodoHeader>
    <TodoMain 
      :list="list" 
      :select="select" 
      @changeDone="changeDone" 
      @delTodo="delTodo"
      @checkAll="checkAll"
    ></TodoMain>
    <TodoFooter 
      :list="list"
      :active="active"
      @clearCompleted="clearCompleted"
      @changeActive="changeActive"
    ></TodoFooter>
  </div>
</template>

<style lang="less" scoped></style>